package com.businessportal.web.controllers.filebrowser;

import com.businessportal.web.dataaccess.entities.Event;
import com.businessportal.web.dataaccess.entities.Login;
import com.businessportal.web.dataaccess.entities.Uploads;
import com.businessportal.web.dataaccess.services.EventService;
import com.businessportal.web.dataaccess.services.UploadsService;
import com.businessportal.web.dataaccess.services.UserService;
import org.apache.commons.io.FileSystemUtils;
import org.apache.commons.io.FileUtils;
import org.json.simple.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;

/**
 * Created by Vadim on 7/21/14.
 */

@WebServlet(urlPatterns = "/securepages/uploads_edit.do")
public class UploadsEditorController  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            req.setCharacterEncoding("UTF-8");

            HttpSession session = req.getSession();
            Login user = (Login)session.getAttribute("user");
            if(null == user){
                throw new Exception("You are not authorized.");
            }

            req.setAttribute("uploads", UploadsService.INSTANCE.getAllUploadsForUser(user));

        } catch(Exception e){
            req.setAttribute("errors", e.getMessage());
            req.setAttribute("uploads", new HashSet<Uploads>());
        }

        getServletContext().getRequestDispatcher("/securepages/uploads_edit.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");

        JSONObject retVal=new JSONObject();

        try {

            String uploadId = req.getParameter("uploadId");

            if(null!= uploadId && !uploadId.isEmpty()){

                Login user = UserService.INSTANCE.CheckLoginPass("login0", "Password");

                Uploads currUpld = UploadsService.INSTANCE.getBiId(Long.parseLong(uploadId));

                File file = new File(currUpld.getLocalFilePath());

                if(file.exists()){
                    FileUtils.forceDelete(file);
                }

                UploadsService.INSTANCE.delete(currUpld);

                retVal.put("message", "OK");
            } else {
                retVal.put("message", "Not found");
            }

        }catch (Exception e){
            retVal.put("error", e.getMessage());
        }

        resp.getWriter().write(retVal.toString());
    }

}
